package com.bjwl.wybx;

import com.bjwl.wybx.util.Constants;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@SpringBootApplication
@MapperScan(basePackages = "com.bjwl.wybx.mapper")
public class WybxApplication {

	public static void main(String[] args) {
		SpringApplication.run(WybxApplication.class, args);
	}

	//跨域设置
	@Bean
	public WebMvcConfigurer corsConfigurer() {

		return new WebMvcConfigurer() {
			/**
			 *添加跨域访问映射路径
			 */
			@Override
			public void addCorsMappings(CorsRegistry registry) {
				registry
						.addMapping("/**")//允许访问当前项目所有路径
						//.allowedOrigins("*")//允许任何域名使用
						.allowedHeaders("*")//允许任何头
						.allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")//允许跨域访问所有类型的请求
						.allowCredentials(true)//是否允许使用跨域凭证
						.maxAge(3600);//跨允许时间

			}

			/**
			 * 添加拦截器设置
			 * 参数：拦截器注册类对象
			 */
			@Override
			public void addInterceptors(InterceptorRegistry registry) {
				//像拦截器注册类对象中添加一个拦截器
				registry.addInterceptor(
						new HandlerInterceptor() {
							/**
							 *  通过此方法拦截未登录用户，未登录用户跳转到登录页面
							 * 在执行控制器前执行该方法
							 * 该方法返回false，表示不允许通过
							 * 该方法返回true，表示放行，继续执行原请求
							 * @throws IOException
							 */
							@Override
							public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
								System.out.println("拦截器被执行");
								if("OPTIONS".equals(request.getMethod().toUpperCase())) {
									return true;
								}

								HttpSession session=request.getSession();
								String s= session.getId();
								System.out.println("s:"+s);
								Object obj= session.getAttribute(Constants.SESSION_ATTR_CURRUSER);
								System.out.println("obj:"+obj);
								if (obj == null) {
									System.out.println("未登录");
									//session为空，属于未 登录用户
									//访问控制器，给前端传一个Json对象，表示用户未登录,让前端跳转到登录页面
//									response.sendRedirect("/safty/login/isLogin");
									return false;

								}

								System.out.println("用户已登录");
								return true;
							};

						}).addPathPatterns("/**")//添加拦截路径，拦截所有请求
						.excludePathPatterns("/safty/login/**");
//						.excludePathPatterns("/safty/user/register");
				//.excludePathPatterns("/safty/login/**") //排除登录下的映射路径
				//.excludePathPatterns("/safty/users/register");

			}
		};
	}
}
